<?php
/**
 * CreateTime: 2023/5/31 10:04
 */

namespace App\Http\Controllers\MeMediator;

use App\Consts\MeLawCaseConsts\MeLawCaseLetterConsts;
use App\Consts\MeLawCaseConsts\MeLawCaseListConsts;
use App\Consts\ResponseConsts\ResponseStatusConsts;
use App\Consts\TableConsts\TableConsts;
use App\Func\AppFunc;
use App\Func\EncryptionFunc;
use App\Func\FileFunc;
use App\Func\ResponseFunc;
use App\Func\TokenFuc;
use App\Http\pkConfig\login\PkLoginConfigGet;
use App\Http\Requests\ListBasicRequest;
use App\Http\Requests\MeLawCase\UpdateLatterInfoRequest;
use App\Models\LatterCache\MeSendLatterCacheModel;
use App\Models\MeLawCase\MeLawCase;
use App\Models\MeLawCase\MeLawCaseLawLetterModel;
use App\Models\MeLawCase\MeLawCaseLawLetterZZModel;
use App\Models\ShortLink\ShortLinkModel;
use App\Scopes\MediationCompanyIdScope;
use App\Scopes\MediationStaffScope;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Storage;

class MeMediationLetterController
{
    public function downloadLatter($pdfHashCode){
        $data = request()->all();
         // 律师函查验码 身份证号后4位
//        $code = $data['code'] ?? "";
//        if(mb_strlen($code)!=6){
//            die("调解函不存在或，身份信息不匹配");
//        }
        // 暂时不查验
        // 根据hash查询
        $lawCaseLawLatterModel = new MeLawCaseLawLetterModel();
        $latterInfo = $lawCaseLawLatterModel->getInfoByHash($pdfHashCode);
        if(!$latterInfo){
            die("调解函不存在或，身份信息不匹配");
        }
        // 获取案件详情
//         $lawCaseInfoModel = new MeLawCase();
//        $lawCaseInfo = $lawCaseInfoModel->select(['respondent_id_card'])->getById($latterInfo['law_case_id']);
//        if(!isset($lawCaseInfo['respondent_id_card'])){
//            die("调解函不存在或，身份信息不匹配");
//        }else if(strtoupper(substr($lawCaseInfo['respondent_id_card'], -6)) != strtoupper($code)){
//            die("调解函不存在或，身份信息不匹配");
//        }
        return Storage::download($latterInfo['pdf_water_path'], "函".$latterInfo['latter_nums'].".pdf");
    }

    public function getLawCaseToLetterHash(){
        $data = request()->all();
        $hash_id = $data['id'];
        // 律师函查验码 身份证号后6位
        $code = $data['code'] ?? "";
        if(mb_strlen($code)!=6){
            return json_encode([
                'ok' => false
            ],256);
        }

        // 暂时不查验
        // 根据hash查询
        $lawCaseLawLatterModel = new MeLawCaseLawLetterModel();
        $latterInfo = $lawCaseLawLatterModel->getInfoByHash($hash_id);
        if(!$latterInfo){
            return [
                'ok' => false
            ];
        }
        // 获取案件详情
        $lawCaseInfoModel = new MeLawCase();
        $lawCaseInfo = $lawCaseInfoModel->getById($latterInfo['law_case_id'],['respondent_id_card']);

        if(!isset($lawCaseInfo['respondent_id_card'])){
            return[
                'ok' => false
            ];
        }else if(strtoupper(substr($lawCaseInfo['respondent_id_card'], -6)) != strtoupper($code)){
            return [
                'ok' => false
            ];
        }

        // 取出所有图片
        $images = Storage::disk('local')->files($latterInfo['file_image_dir']);

        $reqImages = [];
        foreach ($images as $image) {
            // 获取图片内容并进行 base64 编码
            $base64Image = base64_encode(Storage::disk('local')->get($image));
            // 输出 base64 编码后的图片
            $reqImages[] = $base64Image;
        }

        return [
            'ok' =>true,
            'latter_nums' => $latterInfo['latter_nums'],
            'latter_hash' => $latterInfo['pdf_path_hash'],
            'created_time' => $latterInfo['created_time'],
            'images' => $reqImages
        ];
    }

    public function redirect($shortLinkUrl){
        $shortLinkModel = new ShortLinkModel();
        $res = $shortLinkModel->getUrlByShortLinkUrl($shortLinkUrl);
        if($res){
            return Redirect::to($res['url']);
        }else{
            die("当前地址不存在或已过期");
        }
    }

    public function pushLawCaseToLetterOld(){
        $data = request()->all();
        $type = $data['type'] ?? 1;
        switch ($type){
            case 1:
                # 律师函电子版
                $listName = MeLawCaseListConsts::LAW_LATTER_R_LIST_KEY;
                $listHasName = MeLawCaseListConsts::LAW_LATTER_R_HAS_KEY;
            break;
            case 2:
                # 律师函纸质版
                $listName = MeLawCaseListConsts::LAW_LATTER_R_LIST_ZZ_KEY;
                $listHasName = MeLawCaseListConsts::LAW_LATTER_R_HAS_ZZ_KEY;
            break;
        }
        $list = app()->gcHelper->gfGetRedis()->list($listName);
        // 校验当前这些案件是否已经发送过调解函了 如果已经发送过了 则不添加进队列
        $listLawCase = $data['law_case_ids'];
        // 向 set 中添加元素
        try {
            foreach($listLawCase as $value){
                // 判断元素是否存在于 set 中 如果存在跳过
//                $exists = Redis::sismember('mediation_center_key_send_letter_id', $value);
//                if($exists){
//                    continue;
//                }
                Redis::sadd($listHasName, $value);
                $list->push($value);
            }
            return ResponseFunc::returnJson(
                'ok',
                null,
                '添加调解函发送队列成功',
                200
            );
        }catch (\Exception $exception){
            dd($exception);
        }
    }

    public function pushLawCaseToLetter(){
        $data = request()->all();
        $type = $data['type'] ?? 1;
        $letter_type = $data['letter_type'] ?? MeLawCaseLetterConsts::ME_LETTER_TYPE_LAW_CONSTS;
        // 校验当前这些案件是否已经发送过调解函了 如果已经发送过了 则不添加进队列
        $listLawCase = $data['law_case_ids'];
        try {
            // 过滤已经发送过的
            $meSendLetterCacheModel = new MeSendLatterCacheModel();
            $meLawCase = new MeLawCase();
            // 查询已经发送过的的函件 然后用diff区分  返回一个数组，包含了第一个数组中存在而其他数组中不存在的值。
            $checkSendLetter = [];
            // 校验当前这一批案件是否同属于一个委托方
            // 抽取第一个案件作为参考查询委托方信息
            $lawCaseId = $listLawCase[0];
            $lawCaseInfo = $meLawCase->getById($lawCaseId,[
                'client_id'
            ]);
            $checkClient = $meLawCase->select([
                'law_case_id'
            ])->whereIn('law_case_id',$data['law_case_ids'])
            ->where('client_id','!=',$lawCaseInfo['client_id'])
            ->get();
            if(!!count($checkClient)){
                return ResponseFunc::returnJson(
                    'error',
                    null,
                    '同一批次有且仅有一个委托方',
                    200
                );
            }
            // 校验当前任务是否已经被添加处理过了
            // 暂时不做这一步的处理
//            switch ($type){
//                case 1:
//                    $checkSendLetter = $meLawCase->select([
//                        'law_case_id'
//                    ])->whereIn('law_case_id',$data['law_case_ids'])
//                        ->where('is_send_law_latter',1)
//                        ->get()->toArray();
//                    $checkSendLetter = array_column($checkSendLetter,'law_case_id');
//                break;
//                case 2:
//                    $checkSendLetter = $meLawCase->select([
//                        'law_case_id'
//                    ])->whereIn('law_case_id',$data['law_case_ids'])
//                    ->where('is_send_zz_law_letter',1)
//                    ->get()
//                    ->toArray();
//                    $checkSendLetter = array_column($checkSendLetter,'law_case_id');
//                break;
//            }
//            $diff = array_diff($data['law_case_ids'],$checkSendLetter);
            $companyId = TokenFuc::getCurrentStaffInfo()['company_id'];
            $meSendLetterCacheModel->add([
                'client_id' => $lawCaseInfo['client_id'],
                'code' => md5($lawCaseInfo['client_id'].$companyId.time()),
                'letter_ids' => implode(',',$data['law_case_ids']),
                'letter_status' => 1,
                // 记录真实的ids
                'letter_count' => count($data['law_case_ids']),
                'letter_type' => $letter_type,
                'company_id' => $companyId,
                'type' => $type
            ]);

            return ResponseFunc::returnJson(
                'ok',
                null,
                '添加调解函发送队列成功',
                200
            );
        }catch (\Exception $exception){
            dd($exception);
        }
    }

    public function updateLatterRead($pdfHashCode,UpdateLatterInfoRequest $request){
        try {
            $data = $request->all();
            $lawCaseLawLatterModel = new MeLawCaseLawLetterModel();
            $data['read_time'] = date("Y-m-d H:i:s",(($data['read_time']/1000) + (28800)) );
            $latterInfo = $lawCaseLawLatterModel->getInfoByHash($pdfHashCode);
            if(!$latterInfo){
                die("调解函不存在或，身份信息不匹配");
            }
            $updateInfo = [
                'browser' => $data['browser'],
                'recently_read_time' => $data['read_time']
            ];
            // 获取第一次浏览日期
            if(!$latterInfo['read_time']){
                $updateInfo['read_time'] = $data['read_time'];
            }
            // 判断当前进度是否是最大浏览进度
            if($latterInfo['progress']<$data['progress']){
                $updateInfo['progress'] = $data['progress'];
            }

            $updateInfo['duration'] = $latterInfo['duration'] + (double)$data['duration'];
            $updateInfo['read_count'] = $latterInfo['read_count'] + 1;
            $lawCaseLawLatterModel->where('law_case_law_letter_id',$latterInfo['law_case_law_letter_id'])->update($updateInfo);
            return ResponseFunc::returnJson(
                'ok',
                null,
                '修改律师函阅读信息成功',
                200
            );
        }catch (\Exception $exception){
            return ResponseFunc::returnJson(
                'error',
                null,
                '修改律师函阅读信息失败',
                200
            );
        }
    }

    public function smsc(){
        return "OK";
    }

    public function updateStatus(){
        $letterCacheModel = new MeSendLatterCacheModel();
        // 获取所有生成中的调解函 3纸质函 5调解函
        $sendCache = $letterCacheModel->where(function($query){
            $query->where('letter_status',3);
            $query->orWhere('letter_status',5);
        })->get()->toArray();
//        dd($sendCache);
        $lawCaseModel = new MeLawCase();
        $companyId = TokenFuc::getCurrentStaffInfo()['company_id'];
        foreach($sendCache as $value){
            if($value['type'] == 1){
                $count = $lawCaseModel
                    ->where('is_send_law_latter',2)
                    ->whereIn('law_case_id',explode(',',$value['letter_ids']))
                    ->count();
                if($count===0){
                    $letterCacheModel->where('send_letter_cache_id',$value['send_letter_cache_id'])->update([
                        'letter_status' => 6
                    ]);
                }
            }else{
                $count = $lawCaseModel
                    ->where('is_send_zz_law_letter',2)
                    ->whereIn('law_case_id',explode(',',$value['letter_ids']))
                    ->count();
                if($count===0){
                    $letterCacheModel->where('send_letter_cache_id',$value['send_letter_cache_id'])->update([
                        'letter_status' => 4
                    ]);
                }
            }
        }
        return ResponseFunc::returnJson(
            'ok',
            null,
            '更新调解函状态成功',
            200
        );
    }

    public function downPaperLetter($send_letter_cache_id){
        $data =  request()->all();
        // Trans-toc
        $code1 = $data['utk'];
        // 解密token
        // 通过Rsa解密获取redis中正确的key
        $encryptionFunc = new EncryptionFunc();
        $adminLoginPkConfig = new PkLoginConfigGet();
        $redisKey = $encryptionFunc->rsaToBase64Decode($adminLoginPkConfig->getPrKey(),$code1);
        $isExist = Redis::exists($redisKey);
        if($isExist){
            $staffInfo = unserialize(Redis::get($redisKey));
        }else{
            return ResponseFunc::returnJson(
                'error',
                null,
                "缺少权限，下载失败",
                ResponseStatusConsts::OK_200_RESPONSE_STATUS
            );
        }

        $letterCacheModel = new MeSendLatterCacheModel();

        $isExist = $letterCacheModel->isExistByCondition([
            'letter_status'=> 7,
            'send_letter_cache_id' => $send_letter_cache_id
        ]);
        if($isExist){
            return ResponseFunc::returnJson(
                'error',
                null,
                '调解函审核未通过',
                200
            );
        }


        $letterInfo = $letterCacheModel
//            ->withoutGlobalScope(MediationStaffScope::class)
            ->where('send_letter_cache_id',$send_letter_cache_id)
//            ->where('letter_status',4)
            ->first();

        if(!$letterInfo){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前案件批次不存在或不为纸质函',
                200
            );
        }

        // 校验已经生成的纸质函和当前批次数量是否一致 若不一致返回正在生成 若一致则添加进压缩包
        $letterZzModel = new MeLawCaseLawLetterZZModel();
        // 创建临时表
        $ids = explode(',',$letterInfo['letter_ids']);
        $countIds = count($ids);
        DB::statement('CREATE TEMPORARY TABLE cy_temp_ids (fa_id INT, INDEX idx_fa_id (fa_id))');
        // 处理临时表中的数据
        $newArray = array_map(function($value) {
            return ['fa_id' => $value];
        }, $ids);

        // 插入数据到临时表
        DB::table('temp_ids')->insert($newArray);

        $lawCaseList = $letterZzModel->select([
            'law_case_id',
            'law_case_law_letter_id',
            'pdf_path',
        ])
        ->join('temp_ids','law_case_id','temp_ids.fa_id')
        ->withoutGlobalScopes()
        ->get()
        ->toArray();
        // 判断当前一批次纸质函是否已经生成了
        // 去重
        $diffList = array_column($lawCaseList,null,'law_case_id');

        if(count($diffList)!=$countIds){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前纸质函正在处理中',
                200
            );
        }

        // 获取文件下载路径
        $filePath = [];
        foreach($diffList as $value){
            $filePath[] = $value['pdf_path'];
        }

        // 开始下载
        $fileFunc = new FileFunc();
        $paperInfo = $fileFunc->zipFiles($filePath,$send_letter_cache_id);
        if(!$paperInfo['flag']){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前生成压缩包不成功',
                200
            );
        }
        $newPath = str_replace(Storage::path(''),'',$paperInfo['path']);
        return Storage::download($newPath, basename($newPath).".zip");
    }

    public function checkerPaperLetter($send_letter_cache_id){
        $data =  request()->all();
        $letterCacheModel = new MeSendLatterCacheModel();

        $isExist = $letterCacheModel->isExistByCondition([
            'letter_status'=> 7,
            'send_letter_cache_id' => $send_letter_cache_id
        ]);
        if($isExist){
            return ResponseFunc::returnJson(
                'error',
                null,
                '调解函审核未通过',
                200
            );
        }


        $letterInfo = $letterCacheModel
//            ->withoutGlobalScope(MediationStaffScope::class)
            ->where('send_letter_cache_id',$send_letter_cache_id)
//            ->where('letter_status',4)
            ->first();

        if(!$letterInfo){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前案件批次不存在或不为纸质函',
                200
            );
        }

        // 校验已经生成的纸质函和当前批次数量是否一致 若不一致返回正在生成 若一致则添加进压缩包
        $letterZzModel = new MeLawCaseLawLetterZZModel();
        // 创建临时表
        $ids = explode(',',$letterInfo['letter_ids']);
        $countIds = count($ids);
        DB::statement('CREATE TEMPORARY TABLE cy_temp_ids (fa_id INT, INDEX idx_fa_id (fa_id))');
        // 处理临时表中的数据
        $newArray = array_map(function($value) {
            return ['fa_id' => $value];
        }, $ids);

        // 插入数据到临时表
        DB::table('temp_ids')->insert($newArray);

        $lawCaseList = $letterZzModel->select([
            'law_case_id',
            'law_case_law_letter_id',
            'pdf_path',
        ])
        ->join('temp_ids','law_case_id','temp_ids.fa_id')
        ->withoutGlobalScopes()
        ->get()
        ->toArray();
        // 判断当前一批次纸质函是否已经生成了
        // 去重
        $diffList = array_column($lawCaseList,null,'law_case_id');

        if(count($diffList)!=$countIds){
            return ResponseFunc::returnJson(
                'error',
                null,
                '当前纸质函正在处理中',
                200
            );
        }

        return ResponseFunc::returnJson(
            'ok',
            null,
            '正在生成压缩包',
            200
        );
    }

    public function paperTaskList(ListBasicRequest $request){
        $pageSize = $request->get('page_size');
        $letterCacheModel = new MeSendLatterCacheModel();
        $companyId = TokenFuc::getCurrentStaffInfo()['company_id'];
        $res = $letterCacheModel->select([
            "send_letter_cache_id",
            "send_letter_cache_id as key",
            "admin_send_letter_cache.client_id",
            "letter_status as latter_status",
            "code",
            "letter_type",
            "letter_count",
            "client.client_name"
        ])
            ->leftJoin(TableConsts::ME_CLIENT,'client.client_id','admin_send_letter_cache.client_id')
            ->where('company_id',$companyId)
        ->orderBy("send_letter_cache_id",'DESC')
        ->Paginate($pageSize);
        $fmtRes = [];
        if($res){
            $fmtRes = $res->toArray();
            foreach($fmtRes['data'] as $key => $value){
                $fmtRes['data'][$key]['latter_status_str'] = $this->getLatterStatusConsts($value['latter_status']);
            }
        }
        return ResponseFunc::returnJson(
            'ok',
            $fmtRes,
            '获取调解函队列成功',
            200
        );
    }

    private function getLatterStatusConsts($letter_status){
        switch ($letter_status){
            case 1:
                return "审核中";
            case 2:
                return "已审核";
            case 3:
                return "纸质函生成中";
            case 4:
                return "纸质函生成完毕";
            case 5:
                return "电子函生成中";
            case 6:
                return "电子函生成完毕";
            case 7:
                return "审核不通过";
        }
    }

}